import MovingObj from "./MovingObj";

export default BackGround

import Barrier from "./Barrier";
import EquilateralPolygon from "./EquilateralPolygon";

import {animateIntervalId, game} from "./canvas";
import Polygon, {CollisionDetect} from "./Polygon";

/*
* 规定幕布的尺寸为canvas.width * 400
*
*/
function BackGround(x, y, width, height) {
    this.x = x;
    this.y = y;
    this.height = height;
    this.width = width;
    const xGap = 110;
    //  生成bird
    // this.bird = new Polygon(50, y + this.height / 2, 10, 10, 'green')
    this.bird = new EquilateralPolygon(6, 50, y + height / 2, 10, 0, 'green');
    this.movingObj = new MovingObj(this.bird.x, this.bird.y);

    //  生成障碍
    //  障碍物由一个矩形区域生成，在区域内随机生成多边形作为障碍物
    this.barriers = [];
    for (let i = 0; i < 20; ++i) {
        this.barriers[i] = new Barrier(x + 300 + xGap * i, y, 50, 400);
    }


    this.show = function () {
        this.bird.update();
        this.barriers.forEach(obj => {
            obj.show();
        })
    }

    this.update = function () {
        this.movingObj.update();
        this.bird.x = this.movingObj.x;
        this.bird.y = this.movingObj.y;
        this.bird.ang += 0.02 * Math.PI;
        if (this.bird.ang >= 2 * Math.PI)
            this.bird.ang -= 2 * Math.PI;

        for (let i = 0; i < 20; ++i) {
            this.barriers[i].x = this.barriers[i].x - 2;
            if (this.barriers[i].x + this.barriers[i].width < 0) {
                let tmp = (i + 19) % 20;
                this.barriers[i] = new Barrier(this.barriers[tmp].x + xGap, this.barriers[tmp].y, 50, 400);
            }
        }
        this.bird.update();
        for (let i = 0; i < 20; ++i) {
            this.barriers[i].update();
        }
        if (this.bird.y < this.y || this.bird.y > this.y + this.height) {
            clearInterval(animateIntervalId);
            return false;
        }


        // 做碰撞检测
        let collision = false;
        console.log(collision)
        for (let i = 0; i < 20; ++i) {
            if (this.barriers[i].x > 100) continue;
            if (CollisionDetect(this.barriers[i].upPolygon, this.bird)) {
                collision = true;
                break;
            }
            if (CollisionDetect(this.barriers[i].downPolygon, this.bird)) {
                collision = true;
                break;
            }
        }
        console.log(collision)
        if (collision === true) {
            clearInterval(animateIntervalId);
            console.log(animateIntervalId)
            return false;
        }
        return true;
    }
}
